import {Component, OnDestroy, OnInit} from '@angular/core';
import {AppConstants, Components, MsgConstants, PermissionType} from '../../../constants/constants';
import {MsgResult} from '../../../models/msg-result';
import {Observable} from 'rxjs/Observable';
import {ResponseUtil} from '../../../util/response-util';
import {ActivatedRoute, Router} from '@angular/router';
import {AuthService} from '../../../services/auth.service';
import {DataStorageUtil} from '../../../util/data-storage-util';
import {OnlineService} from '../../../services/online.service';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {Dialog} from '../../../widgets/one-dialog/dialog';
import {Subscription} from 'rxjs/Subscription';
import {StompService} from '@stomp/ng2-stompjs/index';
import {AdminUtilService} from '../../admin/admin-util.service';
import {AlarmSubject} from '../../../util/alarm-subject';
import {AppConfig, RabbitConfig} from '../../../app.config';
import {Message} from '@stomp/stompjs';
import {PortalsService} from '../../portals.service';
import {TreeUtil} from '../../../util/tree-util';
import {MenuSubject} from '../../../subject/menu-subject';

declare var $;

@Component({
  selector: 'app-datav-header',
  templateUrl: './datav-header.component.html',
  styleUrls: ['./datav-header.component.css']
})

export class DatavHeaderComponent implements OnInit, OnDestroy {

  myName: string;
  rabbitName: string;
  warnInfoArr: Array<any> = [];

  clickIndex: number;

// Stream of messages
  private subscription: Subscription;
  private ngSubscription: Subscription;
  public messages: Observable<Message>;
  noAckMessages: Array<Message> = [];

  // Subscription status
  public subscribed: boolean;

  // Array of historic message (bodies)
  public mq: Array<any> = [];

  // A count of messages received
  public count = 0;


  private headStomp: any;
  // menu data
  sysMenu: Array<any> = [];
  menus: Array<any> = [];
  cacheMenus: Array<any> = [];
  menuSysId = '';
  screenSizes = {
    xs: 480,
    sm: 768,
    md: 992,
    lg: 1200
  };
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private authService: AuthService,
    private responseUtil: ResponseUtil,
    private dataStorage: DataStorageUtil,
    private onlineService: OnlineService,
    private dialogService: OneDialogService,
    private adminUtilService: AdminUtilService,
    private alarmSubject: AlarmSubject,
    private menuSubject: MenuSubject,
    private portalsService: PortalsService,
    private treeUtil: TreeUtil
  ) {
    this.headStomp = new StompService(RabbitConfig);
  }


  ngOnInit() {
    this.getName();
    this.subscribeData();
    // this.getRealWarnInfo(); //(angular数据订阅)
    // this.startIntervalWarn();
    // this.subscribeAlarm();
    this.getMenus();
  }
  ngOnDestroy() {
    if ( AppConfig.enableMsgSubscribe ) {
      this.unsubscribe();
      this.unSubscribeAlarm();
    }
  }

  getName() {
    this.onlineService.getAccountName()
      .subscribe(
        result => this.responseUtil.success(result, this.extractAccountName),
        error => this.responseUtil.error(error)
      );
  }

  /**
   * 调用消息推送
   */
  subscribeData() {
    if ( AppConfig.enableMsgSubscribe ) {
      this.onlineService.getAccountName().subscribe(
          result => this.responseUtil.success(result, () => {
            if (result && result.code === MsgConstants.MSG_CODE_OK) {
              this.rabbitName = result.data;
              this.subscribe();
            }
            if (result && result.code !== MsgConstants.MSG_CODE_OK) {
              this.dialogService.info(result.message);
            }
          }),
          error => this.responseUtil.error(error)
        );
    }
  }
  logout() {
    // 退出信息modal框
    const dialog = new Dialog();
    dialog.type = Dialog.DialogType.Info;
    dialog.isModal = true;
    dialog.title = '退出信息';
    dialog.content = '确定退出系统吗？';
    dialog.cancelBtn = '取消';
    dialog.okBtn = '确定';
    dialog.showCancelBtn = true;
    dialog.okBtnFun = this.requestLogout;
    this.dialogService.push(dialog);

  }
  /**
   * 确认退出时，回调的请求退出方法
   */
  private requestLogout = () => {
    this.authService.logout().subscribe(
      result => this.responseUtil.success(result, this.processResult),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * 成功时，跳转到登录页面
   * @param result
   */

  private processResult = (result: MsgResult) => {
    if (result.code === MsgConstants.MSG_CODE_OK) {
      this.dataStorage.clear();
      this.router.navigateByUrl(Components.authenComponent);
    }
  }
  /**
   *跳转到个人中心页面
   * @param result
   */
  jumpMe() {
    this.router.navigate(['me'], { relativeTo: this.route});
  }

  /**
   * 数据订阅
   */
  private subscribeAlarm() {
    this.ngSubscription = this.alarmSubject.subscribeData().subscribe(
      (data) => {
        console.log('数据订阅');
        console.log(data);
      }
    );
  }
  private unSubscribeAlarm() {
    console.log('取消订阅');
    // this.ngSubscription.unsubscribe();
  }
  /**
   * 提取账户名
   * @param result
   */
  private extractAccountName = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.myName = result.data;
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 收缩报警信息
   * @param result
   */
  warnInfo(elem) {
    console.log($(elem).siblings('.dropdown-menu'));
    if ($(elem).siblings('.dropdown-menu').css('display') === 'none') {
      $(elem).siblings('.dropdown-menu').show();
    }else {
      $(elem).siblings('.dropdown-menu').hide();
    }
  }
  /**
   * 获取报警信息(angular数据订阅)
   * @param result
   */
  getRealWarnInfo() {
    this.adminUtilService.getWarnSiteInfo()
      .subscribe(
        result => this.responseUtil.success(result, this.progressWarnInfo),
        error => this.responseUtil.error(error)
      );
  }
  private progressWarnInfo = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.warnInfoArr = result.data;
        // this.alarmSubject.pushData(result.data);
      }else {
        this.warnInfoArr = [];
      }
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取报警信息(消息推送)
   * @param result
   */
  public subscribe() {
    console.log('订阅消息推送');
    if (this.subscribed) {
      return;
    }
    // Stream of messages
    this.messages = this.headStomp.subscribe('/queue/' + this.rabbitName, RabbitConfig.headers);

    // Subscribe a function to be run on_next message
    this.subscription = this.messages.subscribe(this.on_next);
  }
  /** Consume a message from the _stompService */
  public on_next = (message: Message) => {
    const mes = JSON.parse(message.body);
    mes.logId = mes.id;
    mes.mesHeader = message.headers;
    mes.client = this.headStomp.client;
    // mes.messageId = message.headers['message-id'];
    // mes.subscription = message.headers.subscription;
    this.warnInfoArr.unshift(mes);
    const dataArr = [];
    dataArr.push(mes);
    this.alarmSubject.pushData(this.warnInfoArr);
    // Count it
    this.count++;
    this.noAckMessages.push(message);
    // Log it to the console
    // let messagId = message.headers['message-id'];
    // Log it to the console
    // this.onSendMessage(mes.id);
  }
  public onSendMessage(message: string) {

    this.headStomp.publish('alarmReplyTo',
      `${message}`);
  }
  public setAckMessage = ( header ) => {
    if (!!header) {
      console.log(this.headStomp.client);
      this.headStomp.client.ack(header['message-id'], header.subscription, header);
      // message.ack();
    }
  };
  public unsubscribe() {
    console.log('取消消息推送');
    if (!this.subscribed) {
      return;
    }

    // This will internally unsubscribe from Stomp Broker
    // There are two subscriptions - one created explicitly, the other created in the template by use of 'async'
    this.subscription.unsubscribe();
    this.subscription = null;
    this.messages = null;
    this.noAckMessages = null;
    this.mq = null;

    this.subscribed = false;
    this.headStomp.disconnect();
  }
  /**
   * 跳转到报警历史记录
   * @param result
   */
  jumpHistoryRecord(elem) {
    this.warnInfoArr = [];
    this.router.navigate(['./admin/msg/alarmrecord/record'], { relativeTo: this.route});
  }
  /**
   * 跳转到报警详情
   * @param result
   */
  jumpRecordDetail(elem, data) {
    this.updateRecordStatus(data.contentId, data.logId);
    $(elem).parents('.dropdown-menu').hide();
  }
  /**
   * 修改报警信息状态
   * @param result
   */
  updateRecordStatus(contentId, logId) {
    this.adminUtilService.putWarnSiteStatus(logId)
      .subscribe(
        result => this.responseUtil.success(result, () => {
          if (result && result.code === MsgConstants.MSG_CODE_OK) {
            const routerUrl = this.router.url;
            if (routerUrl.indexOf('warnType=warn') === -1) {
              this.warnInfoArr.every((data, i) => {
                if ( logId === data.logId) {
                  this.warnInfoArr.splice(i, 1);
                  this.setAckMessage(this.warnInfoArr[i].mesHeader);
                  return false;
                }
              });
              this.alarmSubject.pushData(this.warnInfoArr);
            }else {
              this.dialogService.info('请处理当前报警信息');
            }
            this.router.navigate(['admin/msg/alarmrecord/record/deal', {id: contentId, warnType: 'warn'}], { relativeTo: this.route});
          }
          if (result && result.code !== MsgConstants.MSG_CODE_OK) {
            this.dialogService.info(result.message);
          }
        }),
        error => this.responseUtil.error(error)
      );
  }

  dropDownHide = (e) => {
    $(e.target).children('.dropdown-menu').hide();
  }

  /**
   * 获取菜单
   */
  private getMenus() {
    this.getMenusByConfig().subscribe(
      result => this.responseUtil.success(result, this.process),
      error => this.responseUtil.error(error)
    );
  }

  private getMenusByConfig(): Observable<any> {
    if (AppConstants.sysId) {
      return this.portalsService.getChildMenus(AppConstants.sysId);
    }else {
      return this.portalsService.getPermissions(PermissionType.menus);
    }
  }

  private process = (result: MsgResult) => {
    const rootId = AppConstants.sysId ? AppConstants.sysId : null;
    if (!rootId) {
      if (result.data && result.data.length > 0) {
        this.cacheMenus = result.data;
        this.sysMenu = this.cacheMenus.filter((val) => {
          return  val.type === '0'
        });
        if (this.sysMenu.length > 0) {
          this.menuSubject.pushData(this.sysMenu[0].id);
          this.menuSysId = this.sysMenu[0].id;
        }
        if (AppConfig.enableCollapseSidebar) {
          this.collapseSidebar();
        }
      }
    }
  };

  /**
   * 设置左侧菜单系统ID
   * @param sysId
   */
  setSysMenu(sysId) {
    this.menuSubject.pushData(sysId);
    this.menuSysId = sysId;
  }


  /**
   * 展开侧边栏
   */
  expandedSidebar = () => {
    if ($(window).width() > (this.screenSizes.sm - 1)) {
      if ($('body').hasClass('sidebar-collapse')) {
        $('body').removeClass('sidebar-collapse').addClass('sidebar-expanded-on-hover');
      }
    } else {
      if (!$('body').hasClass('sidebar-open'))  {
        $('body').addClass('sidebar-open').addClass('sidebar-expanded-on-hover');
      }
    }
  };

  /**
   * 收回侧边栏
   */
  collapseSidebar = () => {
    console.log(this.screenSizes);
    if ($(window).width() > (this.screenSizes.sm - 1)) {
      if (!$('body').hasClass('sidebar-collapse')) {
        $('body')
          .addClass('sidebar-collapse')
          .removeClass('sidebar-expanded-on-hover');
      } else {
        if ($('body').hasClass('sidebar-open')) {
          $('body')
            .removeClass('sidebar-open')
            .removeClass('sidebar-expanded-on-hover')
            .addClass('sidebar-collapse');
        }
      }
      this.resetTableWidth();
    }
  };
  resetTableWidth = () => {
    setTimeout(() => {
      const tableWidth = $('.one-table-area .fixed-table-body>.table').outerWidth();
      console.log(tableWidth);
      $('.one-table-area .fixed-table-header>.table').css('width', tableWidth + 'px');
    }, 320)
  };
}
